package com.huabo.weixin;

import com.huabo.utils.KeyUtils;
import org.apache.commons.io.IOUtils;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.CookieStore;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.cookie.BasicClientCookie;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

/**
 * Created by Jackie Liu on 2017/8/19.
 */
public class WXHttpHelper {

    protected static Logger logger = Logger.getLogger(WXHttpHelper.class);
    public static CookieStore cookieStore = new BasicCookieStore();
    public static CloseableHttpClient httpCilent = HttpClients.custom().setDefaultCookieStore(cookieStore).build();

    public static String sendPost(String url, List<BasicNameValuePair> list) {
        // 配置超时时间
        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(1000).setConnectionRequestTimeout(1000)
                .setSocketTimeout(1000).setRedirectsEnabled(true).build();

        HttpPost httpPost = new HttpPost(url);
        // 设置超时时间
        httpPost.setConfig(requestConfig);

        String strResult = "";
        int StatusCode = 404;
        try {
            UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list, "UTF-8");
            // 设置post求情参数
            httpPost.setEntity(entity);
            HttpResponse httpResponse = httpCilent.execute(httpPost);

            if (httpResponse != null) {
                StatusCode = httpResponse.getStatusLine().getStatusCode();
                if (httpResponse.getStatusLine().getStatusCode() == 200) {
                    strResult = EntityUtils.toString(httpResponse.getEntity());
                    logger.info("post/" + StatusCode + ":" + strResult);
                    return strResult;
                } else {
                    strResult = "Error Response: " + httpResponse.getStatusLine().toString();
                    logger.info("post/" + StatusCode + ":" + strResult);
                    strResult = null;
                }
            } else {

            }
        } catch (Exception e) {
            logger.error(e.getMessage());
        } finally {

        }

        return strResult;
    }

    public static String sendJson(String url, String jsonStr) {
        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(1000).setConnectionRequestTimeout(1000)
                .setSocketTimeout(1000).setRedirectsEnabled(true).build();

        HttpPost httpPost = new HttpPost(url);
        httpPost.setConfig(requestConfig);

        StringEntity requestEntity = new StringEntity(jsonStr, "utf-8");
        requestEntity.setContentEncoding("UTF-8");
        httpPost.setHeader("Content-type", "application/json");
        httpPost.setEntity(requestEntity);

        String strResult = "";
        int StatusCode = 404;
        try {
            HttpResponse httpResponse = httpCilent.execute(httpPost);
            if (httpResponse == null) {
                return null;
            }
            StatusCode = httpResponse.getStatusLine().getStatusCode();
            if (httpResponse.getStatusLine().getStatusCode() == 200) {
                strResult = EntityUtils.toString(httpResponse.getEntity());
                return strResult;
            } else {
                strResult = "Error Response: " + httpResponse.getStatusLine().toString();
                logger.info("post/" + StatusCode + ":" + strResult);
                strResult = null;
            }
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
        return strResult;
    }

    /*public static String sendText(String url, String jsonStr) {
        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(1000).setConnectionRequestTimeout(1000)
                .setSocketTimeout(1000).setRedirectsEnabled(true).build();

        HttpPost httpPost = new HttpPost(url);
        httpPost.setConfig(requestConfig);

        StringEntity requestEntity = new StringEntity(jsonStr, "utf-8");
        requestEntity.setContentEncoding("UTF-8");
        httpPost.setHeader("Content-type", "text/plain");
        httpPost.setEntity(requestEntity);

        String strResult = "";
        int StatusCode = 404;
        try {
            HttpResponse httpResponse = httpCilent.execute(httpPost);
            if (httpResponse == null) {
                return null;
            }
            StatusCode = httpResponse.getStatusLine().getStatusCode();
            if (httpResponse.getStatusLine().getStatusCode() == 200) {
                strResult = EntityUtils.toString(httpResponse.getEntity());
                return strResult;
            } else {
                strResult = "Error Response: " + httpResponse.getStatusLine().toString();
                logger.info("post/" + StatusCode + ":" + strResult);
                strResult = null;
            }
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
        return strResult;
    }*/

    public static String sendGet(String url) {
        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(5000) // 设置连接超时时间
                .setConnectionRequestTimeout(5000) // 设置请求超时时间
                .setSocketTimeout(5000).setRedirectsEnabled(true)// 默认允许自动重定向
                .build();
        HttpGet httpGet2 = new HttpGet(url);
        httpGet2.setConfig(requestConfig);
        String srtResult = null;
        int StatusCode = 404;
        try {
            HttpResponse httpResponse = httpCilent.execute(httpGet2);
            StatusCode = httpResponse.getStatusLine().getStatusCode();
            if (httpResponse.getStatusLine().getStatusCode() == 200) {
                srtResult = EntityUtils.toString(httpResponse.getEntity());// 获得返回的结果
                logger.info("get/" + StatusCode + ":" + srtResult);
                return srtResult;
            } else {
                srtResult = EntityUtils.toString(httpResponse.getEntity());// 获得返回的结果
                logger.info("get/" + StatusCode + ":" + srtResult);
                return null;
            }
        } catch (IOException e) {
            logger.error(e);
        } finally {

        }
        return null;
    }

    /**
     * 下载文件
     * @param targetDir 临时保存目录
     * @param downloadUrl 文件链接
     * @return 文件完整路径
     */
    public static String download(String targetDir, String downloadUrl) {
        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(5000) // 设置连接超时时间
                .setConnectionRequestTimeout(5000) // 设置请求超时时间
                .setSocketTimeout(5000).setRedirectsEnabled(true)// 默认允许自动重定向
                .build();
        HttpGet httpGet = new HttpGet(downloadUrl);
        httpGet.setConfig(requestConfig);
        int StatusCode = 404;
        FileOutputStream fileOut = null;
        InputStream is = null;
        try {
            HttpResponse httpResponse = httpCilent.execute(httpGet);
            StatusCode = httpResponse.getStatusLine().getStatusCode();
            if (httpResponse.getStatusLine().getStatusCode() == 200) {
                String fileName = getFileName(httpResponse);
                //System.out.println("file name : " + fileName);
                HttpEntity entity = httpResponse.getEntity();
                is = entity.getContent();
                String filePath = targetDir + fileName;
                File file = new File(filePath);
                fileOut = new FileOutputStream(file);

                int cache = 1024;
                byte[] buffer=new byte[cache];
                int ch = 0;
                while ((ch = is.read(buffer)) != -1) {
                    fileOut.write(buffer,0,ch);
                }
                is.close();
                fileOut.flush();
                return filePath;
            } else {
                String srtResult = EntityUtils.toString(httpResponse.getEntity());// 获得返回的结果
                logger.info("get/" + StatusCode + ":" + srtResult);
            }
        } catch (IOException e) {
            logger.error(e);
        } finally {
            IOUtils.closeQuietly(is);
            IOUtils.closeQuietly(fileOut);
        }
        return null;
    }
    /**
     * 获取response header中Content-Disposition中的filename值
     * @param response
     * @return
     */
    private static String getFileName(HttpResponse response) {
        Header contentHeader = response.getFirstHeader("Content-Type");
        /*System.out.println("contentHeader = " + contentHeader.getValue());
        for (Header header : response.getAllHeaders()) {
            System.out.println(header.getName() + " : " + header.getValue());
        }*/
        if (contentHeader == null) {
            return KeyUtils.getKey();
        }
        String value = contentHeader.getValue().toLowerCase();
        if (value.equals("mpeg4")) {
            value = "mp4";
        }
        return KeyUtils.getKey() + "." + value.split("/")[1];
        /*if (value.startsWith("image")) {
            return KeyUtils.getKey() + "." + value.split("/")[1];
        }
        return KeyUtils.getKey();*/
    }

    public static void setCookieStore(List<BasicClientCookie> cookielist) {
        for (BasicClientCookie cookie : cookielist) {
            WXHttpHelper.cookieStore.addCookie(cookie);
        }
    }

    public static void createCookie(List<BasicClientCookie> cookielist) {
        for (BasicClientCookie cookie : cookielist) {
            WXHttpHelper.cookieStore.addCookie(cookie);
        }
    }

    public static void main(String[] args) {
        WXHttpHelper.download("E:\\files\\", "http://wx.qlogo.cn/mmopen/Q3auHgzwzM4yHkpice3iaFn4tPyib26m9y56W6bebAgmwuGVd8QkhoPbx92OGwGEQVgicGAG3ZnRNuMygORu69aetnY2ibQUxX50ODBPH7O78NLg/0");
    }
}
